package com.mondo.financialwallet.presentation.ui.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.common.ui.BaseActivity;
import com.example.common.utils.TimeCount;
import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.mobsandgeeks.saripaar.annotation.Order;
import com.mondo.financialwallet.R;
import com.mondo.financialwallet.data.DataRepository;
import com.mondo.financialwallet.data.entity.MobilePrefixEntity;
import com.mondo.financialwallet.data.params.RegisterParams;
import com.mondo.financialwallet.data.params.SendMessageParams;
import com.mondo.financialwallet.presentation.ui.window.AreaSelectionPopupWindow;
import com.mondo.financialwallet.presentation.utils.ActivityTitleBarHelper;
import com.mondo.financialwallet.presentation.utils.Toasts;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

public class RegisterActivity extends BaseActivity implements AreaSelectionPopupWindow.OnClickListener {

    public static void launch(Activity activity) {
        activity.startActivity(new Intent(activity, RegisterActivity.class));
    }


    @Order(1)
    @Bind(R.id.mobile_number_edit)
    @NotEmpty(messageResId = R.string.message_please_input_account)
    EditText mMobileNumberEdit;

    @Order(2)
    @Bind(R.id.password_edit)
    @NotEmpty(messageResId = R.string.message_please_enter_your_password)
    EditText mPasswordEdit;

    @Order(3)
    @Bind(R.id.auth_code_edit)
    @NotEmpty(messageResId = R.string.message_please_auth_code)
    EditText mAuthCodeEdit;

    @Order(4)
    @Bind(R.id.invite_code_edit)
    @NotEmpty(messageResId = R.string.message_please_input_invite_code)
    EditText mInviteCodeEdit;

    @Bind(R.id.register_view) Button mRegisterView;
    @Bind(R.id.service_protocol_text) TextView mServiceProtocolText;
    @Bind(R.id.send_verification_code) TextView mSendVerificationCode;
    @Bind(R.id.area_select_layout) View mAreaSelectLayout;
    @Bind(R.id.area_select_anchor_view) View mAreaSelectAnchorView;
    @Bind(R.id.area_number_text) TextView mAreaNumberTextView;


    private ProgressDialog mProgressDialog;
    private AreaSelectionPopupWindow mAreaSelectionPopupWindow;
    private Validator.ValidationListener mRegisterValidationListener =
            new Validator.ValidationListener() {

        @Override
        public void onValidationSucceeded() {
            requestRegister(new RegisterParams(
                    mAreaNumberTextView.getText(),
                    mMobileNumberEdit.getText(),
                    mPasswordEdit.getText(),
                    mAuthCodeEdit.getText(),
                    mInviteCodeEdit.getText())
            );
        }

        @Override
        public void onValidationFailed(List<ValidationError> errors) {
            if (!errors.isEmpty()) {
                Toasts.warning(errors.get(0).getCollatedErrorMessage(
                        RegisterActivity.this));
            }
        }
    };

    @Override
    protected int getBackgroundColor() {
        return Color.WHITE;
    }

    @Override
    protected void setStatusBar() {
        ActivityTitleBarHelper.setWhiteDarkColorStatus(this);
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_register;
    }

    @Override
    protected void initActions() {
        ActivityTitleBarHelper.init(this, R.string.title_register);

        // 跳转协议
        mServiceProtocolText.setOnClickListener(v ->
                WebViewActivity.serviceAgreement(this));

        // 发送验证码
        mSendVerificationCode.setOnClickListener(v -> requestMessageCode());

        // 注册
        Validator registerValidator = new Validator(this);
        registerValidator.setValidationListener(mRegisterValidationListener);
        mRegisterView.setOnClickListener(v -> registerValidator.validate());

        // 显示区号
        mAreaSelectLayout.setOnClickListener(v -> {
            if (mAreaSelectionPopupWindow != null) {
                mAreaSelectionPopupWindow.show(mAreaSelectAnchorView);
            }
        });

        // 手机区号
        requestMobileArea();
    }

    private void requestMobileArea() {
        DataRepository.get().mobilePrefix(result -> {
            if (result.isSuccess()) {
                List<MobilePrefixEntity.DataBean> list = result.getData();
                List<AreaSelectionPopupWindow.Area> areaList = new ArrayList<>();
                for (MobilePrefixEntity.DataBean dataBean : list) {
                    AreaSelectionPopupWindow.Area area = new AreaSelectionPopupWindow.Area(
                            dataBean.getEn_name(), dataBean.getMobile_prefix());
                    areaList.add(area);
                }

                if (mAreaSelectionPopupWindow == null) {
                    mAreaSelectionPopupWindow = new AreaSelectionPopupWindow(this, areaList);
                    mAreaSelectionPopupWindow.setOnClickListener(this);
                }
            }
        });
    }

    private void requestMessageCode() {
        if (TextUtils.isEmpty(mMobileNumberEdit.getText())) {
            Toasts.warning(R.string.message_please_input_account);
            return;
        }

        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog.show(this, null,
                    getString(R.string.message_sending_sms_verification_code));
            DataRepository.get().sendMessageCode(
                    new SendMessageParams(
                            mMobileNumberEdit.getText().toString(),
                            mAreaNumberTextView.getText().toString()),
                    result -> {
                        mProgressDialog.dismiss();
                        mProgressDialog = null;

                        if (result.isSuccess()) {
                            new TimeCount(mSendVerificationCode).start();
                        } else {
                            Toasts.failure(result.getMsg());
                        }
                    }
            );
        }
    }

    private void requestRegister(RegisterParams params) {
        DataRepository.get().register(params, result -> {
            if (result.isSuccess()) {
                startActivityAndFinish(new Intent(this, LoginActivity.class));
                Toasts.success(R.string.title_register);
            } else {
                Toasts.failure(result.getMsg());
            }
        });
    }

    @Override
    public void onClick(String text) {
        mAreaNumberTextView.setText(text);
    }
}
